package main.leetcode.clockin.September;

import main.datastruc.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 113. 路径总和 II
 *
 * <p>给定一个二叉树和一个目标和，找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
 *
 * <p>说明: 叶子节点是指没有子节点的节点。
 */
public class day26 {
    private List<List<Integer>> res;

    public static void main(String[] args) {
        System.out.println(
                new day26()
                        .pathSum(
                                TreeNode.creCmpBTree(
                                        new int[] {5, 4, 8, 11, 0, 13, 4, 7, 2, 0, 0, 0, 0, 5, 1}),
                                22));
    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        dfs(new ArrayList<>(), root, sum);
        return res;
    }

    private void dfs(List<Integer> list, TreeNode root, int remaining) {
        if (root == null) {
            return;
        }

        list.add(root.val);
        if (root.val == remaining && root.left == null && root.right == null) {
            res.add(new ArrayList<>(list));
            list.remove(list.size() - 1);
            return;
        }
        remaining -= root.val;
        dfs(list, root.left, remaining);
        dfs(list, root.right, remaining);
        list.remove(list.size() - 1);
    }
}
